const postModel = require('../models/postModel')
const moment = require('moment')

exports.getAllPost = (req,res)=>{
    //拿到数据
    let data = req.query
    //找model去找需要查询的数据
    postModel.getAllPost(data,(err,result)=>{
        if(err){
            res.json({code:400,msg:'数据查询失败'})
        }else{
            for(var i = 0;i<result.length;i++){
                result[i].created = moment(result[i].created).format('YYYY-MM-DD HH-mm-ss')
            }
            res.json({
                code:200,
                msg:'数据查询成功',
                data:result
            })
        }
    })
}

//处理文章新增的请求
exports.addPost = (req,res) =>{
    //接受get的参数是 req.query  接收post是req.body
    var obj = req.body
    //添加数据库所需要的3个额外的3个数据
    obj.id = null
    obj.views = 0
    obj.likes = 0
    //这个是之前登录成功的时候 保存在的id
    // console.log(req.session.currentUser.id,'--111-------11-----')
    obj.user_id = req.session.currentUser.id

    console.log(obj)
    // 调用数据模块中的方法
    postModel.addPost(obj,(err)=>{
        if(err){
            res.json({
                code:400,msg:'数据新增失败'
            })
        }else{
            res.json({
                code:200,
                msg:'数据新增成功'
            })
        }
    })
}
//根据id获取文章详细数据
exports.getPostById = (req,res)=>{
    //拿到传过来的id
    let id = req.query.id
    postModel.getPostById(id,(err,data)=>{
        if(err){
            res.json({code:400,msg:'查询失败'})
        }else{
            data.created = moment(data.created).format('YYYY-MM-DDTHH:mm')
            res.json({code:200,msg:'查询成功',data})
        }
    })
}

exports.editPostById = (req,res) =>{
    //post请求
    let obj = req.body
    postModel.editPostById(obj,(err)=>{
        if(err){
            res.json({code:400,msg:'文章编辑失败'})
        }else{
            res.json({code:200,msg:'文章编辑成功'})
        }
    })
}

exports.delPostById = (req,res) =>{
    let id = req.query.id
    postModel.delPostById(id,(err)=>{
        console.log(123)
        if(err){
            res.json({code:400,msg:'删除失败'})
        }else{
            res.json({code:200,msg:'删除成功'})
        }
    })
}